import {Howl, Howler} from 'howler';

const names = {
  move: 'Move',
  capture: 'Capture',
  defeat: 'Defeat',
  draw: 'Draw',
  check: 'Check',
  confirmation: 'Confirmation'
};

export class Sounds {
  soundSet: string;
  defaultVolume: number;
  loaded: any;

  constructor(soundSet: string) {
    this.soundSet = soundSet;
    this.defaultVolume = 0.7;

    this.setVolume(this.defaultVolume);
    const baseUrl = 'assets/sound';
    this.loaded = {};

    Object.keys(names).forEach((name) => {
      this[name] = function() {
        if (!this.enabled()) {
          return;
        }
        if (!this.loaded[name]) {
          this.loaded[name] = new Howl({
            src: ['ogg', 'mp3'].map(function(ext) {
              return [baseUrl, names[name] + '.' + ext].join('/');
            }),
            volume: 1
          }).play();
        } else {
          this.loaded[name].play();
        }
      }
    });
  }

  enabled(): boolean {
    return this.soundSet !== 'silent';
  }

  warmup(): void {
    if (this.enabled()) {
      // See goldfire/howler.js#715
      Howler._autoResume();   // This resumes sound if suspended.
      Howler._autoSuspend();  // This starts the 30s timer to suspend.
    }
  }

  setVolume(v: number): void {
    Howler.volume(v);
  }

}